﻿using ClassLibrary1.GeneralPart;
using ClassLibrary1.IService;
using Newtonsoft.Json;
using Senparc.Weixin;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.Entities.Request;
using System;
using System.Web;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace ClassLibrary1.Service
{
    /// <summary>
    /// 微信实现
    /// </summary>
    public class WeChatService : IWeChatService
    {
        // AppId
        public static readonly string AppId = "wxa1d5903f934f72f9";
        // AppSecret
        public static readonly string AppSecret = "9be1885e90aa82b2f865a7c954a1e1a9";
        //Domain
        public static readonly string Domain = "http://mbrq6p.natappfree.cc";
        public static readonly string token = "weixin";

        /// <summary>
        /// 微信授权回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <param name="returnUrl"></param>
        public string BaseCallback(string code, string state, string returnUrl)
        {
            LogHelper.Debug(typeof(string), "进入回调方法");
            LogHelper.Debug(typeof(string), "code:"+code);
            LogHelper.Debug(typeof(string), "state:" + state);
            LogHelper.Debug(typeof(string), "returnUrl:" + returnUrl);
            LogHelper.Debug(typeof(string), "AppId:" + AppId);
            LogHelper.Debug(typeof(string), "AppSecret:" + AppSecret);

            returnUrl = HttpUtility.UrlDecode(returnUrl); 
            try
            {
                if (string.IsNullOrEmpty(code))
                {
                   
                    LogHelper.Debug(typeof(string),"/Message/Error_Param?msg=参数异常");
                }
                else
                {
                    //获取AccessToken  用Code AppId AppSecret
                    var result = OAuthApi.GetAccessToken(AppId, AppSecret, code);//这里报错  没注册服务？
                    if (result.errcode != ReturnCode.请求成功)
                    {
                        LogHelper.Debug(typeof(string), "请求失败");
                    }
                    else
                    {
                        LogHelper.Debug(typeof(string), "access_token"+ result.access_token);
                        LogHelper.Debug(typeof(string), "openid" + result.openid);
                        //获取用户信息 AccessToken   Openid
                        var userInfo = OAuthApi.GetUserInfo(result.access_token, result.openid);
                        LogHelper.Debug(typeof(string), JsonConvert.SerializeObject(userInfo));
                    }
                }
                return returnUrl;
            }
            catch (Exception ex)
            {
                LogHelper.Debug(typeof(string), "回调异常" + ex.Message);
                throw;
            }
        }
        /// <summary>
        ///  获取微信Code
        /// </summary>
        /// <param name="appId">appid</param>
        /// <param name="appSecret">appSecret</param>
        /// <param name="redirectUrl">授权后重定向的回调链接地址</param>
        /// <returns></returns>
        public string GetWeiXinCode(PostModel postModel, string echostr)
        {
            LogHelper.Debug(typeof(string), "进入index方法");
            string str = string.Empty;
            if (CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce,token))
            {
                str=  echostr;
            }
            else
            {
                str="failed:" + postModel.Signature + "," + CheckSignature.GetSignature(postModel.Timestamp, postModel.Nonce, token + "。" +
                  "如果你在浏览器中看到这句话，说明此地址可以被作为微信公众账号后台的Url，请注意保持Token一致。");
            }
            return str;

        }

        public string  Login(string ReturnUrl)
        {
            //这里是请求微信的授权方法，微信授权完，跳转的是你写的BaseCallback方法,returnUrl就是前端页面的跳转地址,然后进入到BaseCallback方法
            LogHelper.Debug(typeof(string), "进入login方法");
            string url = OAuthApi.GetAuthorizeUrl(AppId, Domain + "/Wechat/BaseCallback?returnUrl=" + HttpUtility.UrlEncode(ReturnUrl), "Masoft", OAuthScope.snsapi_userinfo);
            LogHelper.Debug(typeof(string), url);
            return url;
        }

    }
}
